package com.spike.servlet;

import com.spike.model.User;
import com.spike.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService userService = new UserService();
        try {
            User login = userService.findByUP(username, password);
            if (login != null) {
                req.setAttribute("msg", "已经存在该用户名或密码");
//                转发到注册界面
                req.setAttribute("username",username);
                req.setAttribute("password",password);
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
            }else {
//                执行注册方法
                int register = userService.register(username, password);
                if (register > 0) {
                    resp.sendRedirect("/login.jsp");
                }else
                    req.setAttribute("msg", "注册失败");
                    req.setAttribute("username",username);
                    req.setAttribute("password",password);
                    req.getRequestDispatcher("/register.jsp").forward(req, resp);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
